package com.aisino.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.XML;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aisino.util.Logger;
import com.aisino.util.CalculateUtil;
import com.aisino.mapper.KpInvoiceMapper;
import com.aisino.util.ConfigurationUtil;

/**
 * 开票的Service层
 * @author gaomin
 * @date 2018/12/4
 *
 */
@Service
public class KpInvoiceService {
	
	private static final Logger log = Logger.getLogger(KpInvoiceService.class);
	
	@Resource
	private KpInvoiceMapper kpMapper;
	
	/**
	 * 开票方法
	 * @author gaomin
	 * @date 2018/12/5
	 *
	 */
	@SuppressWarnings("finally")
	public String save_taxserverKp(String ohid) {
		String rs = "";
		try {
			String serverUrl = ConfigurationUtil.getValue("serverUrl");
			log.info("开票地址，"+ serverUrl);
			
			//调用TaxServer开票
			String res = save_sendInvoiceInfo(ohid, serverUrl);
			log.info("开票返回信息："+res);
			if("开票成功!".equals(res)){
				
			}
			
			rs += "订单:" +ohid + ":" + res + "\n";
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			log.info("开票完毕返回信息："+rs);
			return rs;
		}
	}
	
	/**
	 * 作废发票方法
	 * @author gaomin
	 * @date 2018/12/5
	 *
	 */
	@SuppressWarnings("finally")
	public String save_taxserverZfKp(String ohid) {
		String rs = "";
		try {
			String serverUrl = ConfigurationUtil.getValue("serverUrl");
			log.info("作废发票地址，"+ serverUrl);
			
			//调用TaxServer开票
			String res = invoiceInvalidInterface(ohid, serverUrl);
			log.info("作废发票返回信息："+res);
			if("200".equals(res)){
				//回写作废成功信息
				HashMap<String, Object> map = kpMapper.selectYfpdm(ohid);
				kpMapper.updateHeadZfLp(map);
				kpMapper.updateHeadZfHp(ohid);
			}
			
			rs += "订单:" +ohid + ":" + res + "\n";
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			log.info("作废发票完毕返回信息："+rs);
			return rs;
		}
	}
	
	
	/**
	 * 调用TaxServer开票方法
	 * @author gaomin
	 * @date 2018/10/26
	 *
	 */
	public String save_sendInvoiceInfo(String ohid, String serverUrl) {
		String msg = ""; // 解析返回消息
		HashMap<String,Object> oh = kpMapper.selectHeadByOhid(ohid);
		String tmp_fpzl = Str(oh.get("FPZL"));
		if ("0".equals(tmp_fpzl)) {
			// 专票
			tmp_fpzl = "8";
		} else if ("2".equals(tmp_fpzl)) {
			// 普票
			tmp_fpzl = "7";
		} else if ("51".equals(tmp_fpzl)) {
			// 电子发票
			tmp_fpzl = "1";
		} else {
			return "错误的发票种类!";
		}

		try {
			URL url = new URL(serverUrl);
			URLConnection urllConnection = url.openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) urllConnection;
			httpUrlConnection.setRequestMethod("POST");
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setConnectTimeout(5*60*1000);	//连接时间
			httpUrlConnection.setRequestProperty("Content-type",
					"application/x-www-form-urlencoded");

			OutputStream os = httpUrlConnection.getOutputStream();

			String params = "";
			params += "Action="
					+ URLEncoder.encode("ECXML.FPKJ.BC.E_INV", "UTF-8"); // Action：开票(ECXML.FPKJ.BC.E_INV)
			params += "&SJLY=09"; // SJLY：09-税控组件开票
			params += "&FPLX=" + tmp_fpzl; // FPLX：发票类型(1-增普电 7-增普 8-增专)
			params += "&FPQQLSH="
					+ ohid; // FPQQLSH：发票请求流水号, 一个订单对应唯一的流水号, 避免重复开票
			String kplx = "0";
			if (StringUtils.isNotEmpty(Str(oh.get("YFPHM")))
					&& StringUtils.isNotEmpty(Str(oh.get("YFPDM")))) {
				kplx = "1";
				//校验冲红发票金额
				boolean is_overRed = chargeChje(Str(oh.get("YFPDM")),Str(oh.get("YFPHM")),new BigDecimal(Str(oh.get("JSHJ"))));
				if (is_overRed) {
					//已超过可冲红金额
					return "冲红金额超过蓝票可冲红金额,冲红失败!";
				}
			}
			params += "&KPLX=" + kplx; // KPLX：开票类型(0-蓝字发票 1-红字发票)
			if ("1".equals(Str(oh.get("HAS_QD")))) {
				// 有清单
				params += "&QD_BZ=1"; // QD_BZ：清单标志(默认为0,1：取清单对应票面内容字段打印到发票票面上)
				params += "&QDXMMC=" + URLEncoder.encode("(详见销货清单)", "UTF-8"); // QDXMMC：清单发票项目名称(清单标识（QD_BZ）为1时必填:

			} else {
				params += "&QD_BZ=0";
				params += "&QDXMMC=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("XFSH")))) {
				params += "&XSF_NSRSBH="
						+ URLEncoder.encode(Str(oh.get("XFSH")), "UTF-8"); // XSF_NSRSBH: 销售方纳税人识别号
			} else {
				params += "&XSF_NSRSBH="; // GMF_NSRSBH: 购买方纳税人识别号
			}
			if (StringUtils.isNotEmpty(Str(oh.get("XFMC")))) {
				params += "&XSF_MC="
						+ URLEncoder.encode(Str(oh.get("XFMC")), "UTF-8"); // XSF_MC: 销售方名称
			} else {
				params += "&XSF_MC=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("XFDZDH")))) {
				params += "&XSF_DZDH="
						+ URLEncoder.encode(Str(oh.get("XFDZDH")), "UTF-8"); // XSF_DZDH: 销售方地址、电话
			} else {
				params += "&XSF_DZDH=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("XFYHZH")))) {
				params += "&XSF_YHZH="
						+ URLEncoder.encode(Str(oh.get("XFYHZH")), "UTF-8"); // XSF_YHZH: 销售方银行账号
			} else {
				params += "&XSF_YHZH=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("GFSH")))) {
				params += "&GMF_NSRSBH=" + Str(oh.get("GFSH")); // GMF_NSRSBH:
															// 购买方纳税人识别号
			} else {
				params += "&GMF_NSRSBH="; // GMF_NSRSBH: 购买方纳税人识别号
			}
			if (StringUtils.isNotEmpty(Str(oh.get("GFMC")))) {
				params += "&GMF_MC="
						+ URLEncoder.encode(Str(oh.get("GFMC")), "UTF-8"); // GMF_MC:
																		// 购买方名称
			} else {
				params += "&GMF_MC=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("GFDZDH")))) {
				params += "&GMF_DZDH="
						+ URLEncoder.encode(Str(oh.get("GFDZDH")), "UTF-8"); // GMF_DZDH=
																		// 购买方地址、电话
			} else {
				params += "&GMF_DZDH=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("GFYHZH")))) {
				params += "&GMF_YHZH="
						+ URLEncoder.encode(Str(oh.get("GFYHZH")), "UTF-8"); // GMF_YHZH:
																		// 购买方银行账号
			} else {
				params += "&GMF_YHZH=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("KPR")))) {
				params += "&KPR=" + URLEncoder.encode(Str(oh.get("KPR")), "UTF-8"); // KPR:
																				// 开票人
			} else {
				params += "&KPR=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("SKR")))) {
				params += "&SKR=" + URLEncoder.encode(Str(oh.get("SKR")), "UTF-8"); // SKR:
																				// 收款人
			} else {
				params += "&SKR=";
			}
			if (StringUtils.isNotEmpty(Str(oh.get("FHR")))) {
				params += "&FHR=" + URLEncoder.encode(Str(oh.get("FHR")), "UTF-8"); // FHR:
																				// 复核人
			} else {
				params += "&FHR=";
			}
			if ("1".equals(kplx)) {
				// 红字
				params += "&YFP_DM=" + Str(oh.get("YFPDM")); // YFP_DM:
														// 原发票代码(红字发票时必须)
				params += "&YFP_HM=" + Str(oh.get("YFPHM")); // YFP_HM:
														// 原发票号码(红字发票时必须)
				
				String redDP = "";	//红字电票
				String redZP = "";	//红字专票
				String redPP = "";	//红字普票
				
				redDP = "1";
				redZP = "1";
				redPP = "1";
				if ("0".equals(Str(oh.get("FPZL"))) && "1".equals(redZP)) {
					//有开红字专票的权限
				} else if ("2".equals(Str(oh.get("FPZL"))) && "1".equals(redPP)) {
					//有开红字普票的权限
				} else if ("51".equals(Str(oh.get("FPZL"))) && "1".equals(redDP)) { 
					//有开红字电票的权限
				} else {
					return "无开具此票种的红字发票权限!";
				}
			} else {
				params += "&YFP_DM="; // YFP_DM: 原发票代码(红字发票时必须)
				params += "&YFP_HM="; // YFP_HM: 原发票号码(红字发票时必须)
				
				String blueDP = "";
				String blueZP = "";
				String bluePP = "";
				
				blueDP = "1";
				blueZP = "1";
				bluePP = "1";
				
				if ("0".equals(Str(oh.get("FPZL"))) && "1".equals(blueZP)) {
					//有开红字专票的权限
				} else if ("2".equals(Str(oh.get("FPZL"))) && "1".equals(bluePP)) {
					//有开红字普票的权限
				} else if ("51".equals(Str(oh.get("FPZL"))) && "1".equals(blueDP)) { 
					//有开红字电票的权限
				} else {
					return "无开具此票种的蓝字发票权限!";
				}
			}
			if (StringUtils.isNotEmpty(Str(oh.get("BZ")))) {
				String bz = Str(oh.get("BZ"));
				if (bz.length() > 130) {
					bz = bz.substring(0, 130);
				}
				params += "&BZ=" + URLEncoder.encode(bz, "UTF-8"); // BZ:备注(红字:对应正数发票代码:XXXXXXXXX号码:YYYYYYYY)
			} else {
				params += "&BZ=";
			}
			params += "&FPZT=0"; // FPZT：发票状态 0 正常发票 1 作废发票
			params += "&TSFS=1"; // TSFS:推送方式（1 电子邮件）
			if ("51".equals(Str(oh.get("FPZL"))) && Str(oh.get("EMAIL")) != null && !"".equals(Str(oh.get("EMAIL")))) {
				params += "&EMAIL=" + Str(oh.get("EMAIL"));
			} else {
				params += "&EMAIL=";
			}
			if ("0".equals(Str(oh.get("FPZL"))) && "1".equals(kplx) ) {
				//专票 红票
				if (StringUtils.isNotEmpty(Str(oh.get("XXB_DH")))) {
					params += "&XXB_DH="+Str(oh.get("XXB_DH"));	//专票红字信息表
				} else {
					httpUrlConnection.disconnect();
					return "开具红字增值税专用发票需填写红字增值税专用发票信息表编号!";
				}
			}
			params += "&RETTYPE=1"; // RETTYPE:结果返回类型(1:json 0:xml)
			params += "&PDF_XZFS=2"; // PDF_XZFS:发票下载方式 1 发票下载地址 2 发票内容BASE64文件流
			params += "&XM_COUNT=" + Integer.parseInt(Str(oh.get("SPHS"))); // XM_COUNT:发票明细条数
			params += "&JSHJ=" + Str(oh.get("JSHJ"));
			
			// 明细拼接
			for (int i = 0; i < Integer.parseInt(Str(oh.get("SPHS"))); i++) {
				List<HashMap<String,Object>> ols = kpMapper.selectLineByOhid(ohid);
				HashMap<String,Object> ol = ols.get(i);
				int j = Integer.parseInt(Str(ol.get("SPXH")));	//商品明细参数行下标
				params += "&XMMC" + j + "="
						+ URLEncoder.encode(Str(ol.get("SPMC")), "UTF-8"); // XMMC1：项目名称1
				if (StringUtils.isNotEmpty(Str(ol.get("DW")))) {
					params += "&DW" + j + "="
							+ URLEncoder.encode(Str(ol.get("DW")), "UTF-8"); // XMMC1：项目名称1
				} else {
					params += "&DW" + j + "=";
				}
				if (StringUtils.isNotEmpty(Str(ol.get("GGXH")))) {
					params += "&GGXH" + j + "="
							+ URLEncoder.encode(Str(ol.get("GGXH")), "UTF-8"); // XMMC1：项目名称1
				} else {
					params += "&GGXH" + j + "=";
				}
				params += "&XMSL" + j + "=" + Str(ol.get("SL")); // 数量
				params += "&XMDJ" + j + "=" + Str(ol.get("BHSDJ")); // 单价
				BigDecimal slv = CalculateUtil.changeSlv(new BigDecimal(Str(ol.get("SLV"))));
				params += "&SL" + j + "=" + slv; // 税率
				params += "&HSBZ" + j + "=0"; // 含税标志
				params += "&XMJE" + j + "=" + Str(ol.get("BHSJE")); // 项目金额
				params += "&SE" + j + "=" + Str(ol.get("SE")); // 税额
				params += "&FPHXZ" + j + "=" + Str(ol.get("SPHXZ")); // 发票行性质:0正常行、1折扣行
				if ("1".equals(Str(ol.get("FPHXZ")))) {
					//折扣行验证紧邻上一行的关系
					HashMap<String,Object> olF = ols.get(i-1);
					//商品名称,税率,税收分类编码
					if (!Str(olF.get("SPMC")).equals(Str(ol.get("SPMC"))) || (new BigDecimal(Str(olF.get("SLV")))).compareTo((new BigDecimal(Str(ol.get("SLV"))))) != 0
						|| !Str(olF.get("SSFLBM")).equals(Str(ol.get("SSFLBM"))) ) {
						return "第"+j+"行折扣行信息错误,请检查!";
					}
				}
				params += "&SPBM" + j + "=" + Str(ol.get("SSFLBM"));
				params += "&ZXBM" + j + "=";
				params += "&YHZCBS" + j + "=" + Str(ol.get("YHZCBS")); // YHZCBS1：优惠政策标识1(0：不使用，1：使用)
				if (StringUtils.isNotEmpty(Str(ol.get("LSLBS")))) {
					params += "&LSLBS" + j + "=" + Str(ol.get("LSLBS")); // LSLBS1：零税率标识1(空：非零税率，
				} else {											// 1：免税，2：不征税，3普通零税率)
					params += "&LSLBS" + j + "=";
				}
				if (StringUtils.isNotEmpty(Str(ol.get("ZZSTSGL")))) {
					params += "&ZZSTSGL" + j + "="
							+ URLEncoder.encode(Str(ol.get("ZZSTSGL")), "UTF-8"); // 增值税特殊管理
				} else {
					params += "&ZZSTSGL" + j + "="; // 增值税特殊管理
				}
				params += "&KCE" + j + "="; // KCE1:扣除额1
			} // 发票明细参数拼接完毕
			
			//log.info(params);
			log.info("Taxserver开票" + params);
			// 发起请求
			os.write(params.getBytes());

			InputStream is = httpUrlConnection.getInputStream();
			byte[] b = new byte[1024];
			int len = 0;
			String s = "";
			while ((len = is.read(b)) != -1) {
				String ss = new String(b, 0, len, "UTF-8");
				s += ss;
			}
			httpUrlConnection.disconnect(); //关闭连接
			// System.out.println("返回:"+URLDecoder.decode(s, "UTF-8"));
			String return_s = "";
			return_s = URLDecoder.decode(s, "UTF-8");
			//log.info("[发票开具]返回结果:"+return_s);
			log.info("发票开具，返回结果:"+return_s);
			String retCode = getReturnCode(return_s)[0];
			if ("200".equals(retCode)) {
				msg = save_invoiceInfo(ohid, return_s);
			} else {
				msg = getReturnCode(return_s)[1];
				HashMap<String,Object> ohead = new HashMap<String,Object>();
				ohead.put("ERRLOG",msg);
				ohead.put("OHID",ohid);
				kpMapper.updateHeadLog(ohead);
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
			msg = e.getMessage();
		} catch (ProtocolException e) {
			e.printStackTrace();
			msg = e.getMessage();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			msg = e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			msg = e.getMessage();
		} catch (Exception e){
			e.printStackTrace();
			msg = e.getMessage();
		}
		finally {
		}
		return msg;
	}
	
	
	
	/**
	 * 
	 * @Title: getReturnCode
	 * @Description: 解析开票接口返回代码
	 * @author 曹梦媛
	 * @date 2018年6月29日 上午11:04:28
	 * @param: @param return_s
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	private String[] getReturnCode(String return_s) {
		JSONObject obj = (JSONObject) JSON.parseObject(return_s);
		JSONObject message = (JSONObject) obj.get("message");
		String value = (String) message.get("value");
		String rtMsg = "";
		if (!"200".equals(value)) {
			rtMsg = message.get("result").toString().replace("'", "''");
		}
		return new String[] { value, rtMsg };
	}
	
	/**
	 * 保存开票信息
	 * @author gaomin
	 * @throws ParseException 
	 * @date 2018/10/26
	 *
	 */
	private String save_invoiceInfo(String ohid, String return_s){
		String msg = "";
		JSONObject obj = (JSONObject) JSON.parseObject(return_s);
		JSONObject message = (JSONObject) obj.get("message");
		String value = (String) message.get("value");
		if ("200".equals(value)) {
			msg = "开票成功!";
			JSONObject result = (JSONObject) message.get("result");
			// 开票成功
			String fpdm = result.get("FP_DM").toString();
			String fphm = result.getString("FP_HM").toString();
			String fpmw = result.getString("FP_MW").toString();
			String jym = result.getString("JYM").toString();
			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = df.parse(result.getString("KPRQ").toString());
				SimpleDateFormat df_result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String kprq = df_result.format(date);
				String fpqqlsh = result.getString("FPQQLSH").toString();
				HashMap<String,Object> oh = new HashMap<String,Object>();
				oh.put("OHID",ohid);
				oh.put("KPRQ",kprq);
				oh.put("FPDM",fpdm);
				oh.put("FPHM",fphm);
				oh.put("FPMW",fpmw);
				oh.put("JYM",jym);
				oh.put("FPQQLSH",fpqqlsh);
				oh.put("ERRLOG","");
				kpMapper.updateHead(oh);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		} else {
			// 开票失败
			String rst = message.get("result").toString().replace("'", "''");
			msg = rst;
		}
		return msg;
	}
	
	public String Str(Object obj){
		String str = "";
		if(obj!=null&&obj!=""){
			str = obj.toString();
		}
		return str;
	}
	
	/**
	 * 
	 * @Title: chargeChje
	 * @Description: 校验本张待开红字发票金额是否超过蓝票未冲金额(价税合计)
	 * @author 曹梦媛
	 * @date 2018年7月3日 下午3:52:23
	 * @param: @param yfpdm
	 * @param: @param yfphm
	 * @param: @param jshj
	 * @param: @return 
	 * @return: boolean   
	 * @throws
	 */
	private boolean chargeChje(String yfpdm, String yfphm, BigDecimal jshj) {
		// 根据发票号码发票代码找到蓝字发票, 并更新冲抵金额
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("YFPDM", yfpdm);
		map.put("YFPHM", yfphm);
		
		HashMap<String,Object> yoh =kpMapper.selectHeadByYFPDM(map);
		
		BigDecimal ycje = new BigDecimal(Str(yoh.get("YCJE"))); //已冲金额
		BigDecimal new_ycje = ycje.subtract(jshj).setScale(CalculateUtil.SCALE,
				BigDecimal.ROUND_HALF_UP);
		if ((new BigDecimal(Str(yoh.get("JSHJ")))).compareTo(new_ycje) != -1 ) {
			//蓝票税价合计大于冲红金额, 未超过
			return false;
		} else {
			//蓝票价税合计小于等于新冲红金额, 已超过
			/*log.info("[开具发票]原发票代码:"+yfpdm+"原发票号码:"+yfphm+"金额:"+yoh.getJshj()+" 已冲金额:"+ycje+" "
					+ "待冲金额:"+jshj+" 红票价税合计已超过可冲红价税合计!");*/
			log.info("发票开具, [开具发票]原发票代码:"+yfpdm+"原发票号码:"+yfphm+"金额:"+Str(yoh.get("JSHJ"))+" 已冲金额:"+ycje+" "
					+ "待冲金额:"+jshj+" 红票价税合计已超过可冲红价税合计!");
			return true;
		}
	}
	
	/**
	 * 发票作废
	 * @author gaomin
	 * @date 2018/12/5
	 *
	 */
	public String invoiceInvalidInterface(String ohid,String serverUrl){
		HashMap<String,Object> oderHead = kpMapper.selectHeadByOhid(ohid);
		
		String value = null;
		String params = "";
		try {
			params += "Action="
					+ URLEncoder.encode("ECXML.FPZF.BC.E_INV", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params += "&SJLY=09";
		String fpzl=Str(oderHead.get("FPZL"));
		if(fpzl.equals("0")){
			params += "&FPLX=" + 8;
		}else if(fpzl.equals("2")){
			params += "&FPLX=" + 7;
		}else if(fpzl.equals("51")){
			params += "&FPLX=" + 1;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fpqqlsh = sdf.format(new Date()) + getRdom(3);
		params += "&FPQQLSH=" + fpqqlsh;
		if(Str(oderHead.get("YFPDM")) != null&&Str(oderHead.get("YFPDM"))!=""
				&& Str(oderHead.get("YFPHM")) != null&&Str(oderHead.get("YFPHM"))!=""){
			params += "&KPLX=1";
		}else{
			params += "&KPLX=0";
		}
//		params += "&KPLX=" + oderHead.getYfpdm() != null
//				&& oderHead.getYfphm() != null ? "1" : "0";
		params += "&YFP_DM=" + Str(oderHead.get("YFPDM"));
		params += "&YFP_HM=" + Str(oderHead.get("YFPHM"));
		JSONObject jsonObject = sendPost(serverUrl, params.toString());
		if(jsonObject==null){
			return null;
		}
		JSONObject message = (JSONObject) jsonObject.get("message");
		if (message.get("value") != null) {
			value = String.valueOf(message.get("value"));
		}
		return value;
	}
	
	//生成随机数
	public static String getRdom(int ws) {
		Random r = new Random();
		String nums = Integer.toString(Math.abs(r.nextInt(Integer.MAX_VALUE)));
		//如果生成的随机数大于等于 10 位， 直接返回截取后的 10 位随机数
		//如果生成的随机数小于 10 位， 前面补 0 足 10 位
		if (nums.length() >= ws)
			return nums.substring(nums.length() - ws);
		else
			return StringUtils.leftPad(nums, ws, "0");
	}
	
	/**
	 * http post请求
	 * 
	 * @param url
	 * @param output
	 *            json串
	 * @return
	 */
	public static JSONObject sendPost(String url, String output) {
		JSONObject jsonObject = null;
		jsonObject = httpRequest(url, "POST", output);
		return jsonObject;
	}
	
	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	private static JSONObject httpRequest(String request, String requestMethod,
			String output) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		try {
			log.info("[HTTP] http请求request:"+request+","
					+ "method:"+requestMethod+",output:"+output);
			// 建立连接
			URL url = new URL(request);

			log.info("url:"+ url);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(30000);
			connection.setUseCaches(false);
			connection.setRequestMethod(requestMethod);
			connection.setRequestProperty("Charsert", "UTF-8");
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			
			
			
			if (output != null) {
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			// 流处理
			//int s = connection.getResponseCode();
			inputStream = connection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String line;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			// 关闭连接、释放资源
			reader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			
			//logger.info("返回信息："+buffer.toString());
			String return_s = URLDecoder.decode(buffer.toString(), "UTF-8");
			log.info("返回信息解码："+return_s);
			org.json.JSONObject json=
			XML.toJSONObject(buffer.toString());
			jsonObject = JSONObject.parseObject(json.toString());
			//jsonObject = XML.toJSONObject(buffer.toString());
			//JSONObject.
		} catch (ProtocolException e) {
			log.error("http请求error:");
			return null;
		} catch (MalformedURLException e) {
			log.error("http请求error:");
			return null;
		} catch (IOException e) {
			log.error("http请求error:");
			return null;
		} finally {
			// 使用finally块来关闭输出流、输入流
			try {
				if (reader != null) {
					reader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				log.error("[HTTP] http请求error:"+ ex.getMessage());
				return null;
			}
		}
		return jsonObject;
	}
	
}
